import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, convertFromHTML, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const confirm = Modal.confirm;
const { TextArea } = Input;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import {
  orderList,
  orderCancel,
  orderConfirm,
  orderPayment,
  orderRefund,
  orderRequest,
  orderSend,
  orderExport,
  orderDetail,
  requestConfirm,
} from '../../services/api';
import { getArrFromObj } from '../../utils/utils';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import counties from '../../data/counties.json';

import styles from './paymentOrder.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const STATUS_MAP = {
  '0': '未支付',
  '1': '待确认',
  '2': '待缴费',
  '3': '已请款',
  '4': '待开票',
  '5': '已完成',
  '10': '已取消',
  '11': '待退款',
  '12': '已退款',
  '31': '请款已确认',
};

const PAY_TYPE_MAP = {
  '1': '微信',
  '0': '支付宝',
  '2': '线下',
};

const PAYMENT_STATUS_ARR = [
  {
    id: 1,
    name: '完成缴费',
  },
  {
    id: 2,
    name: '缴费异常',
  },
];

const NEED_BILLING_ARR = [
  {
    id: 1,
    name: '需要发票',
  },
  {
    id: 2,
    name: '无需发票',
  },
];

const PAY_TYPE_ARR = getArrFromObj(PAY_TYPE_MAP);
const STATUS_ARR = getArrFromObj(STATUS_MAP);

const pageSize = 10;

@connect(({ paymentOrder, loading }) => {
  return {
    paymentOrder,
    loading: loading.models.paymentOrder,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    activeItem: null,

    orderCancel2Show: false,
    orderCancel2Remark: null,

    orderPaymentShow: false,
    paymentStatus: 1,
    orderPaymentRemark: null,

    orderSendShow: false,
    needBilling: 1,
    invoiceAddress: null,
    trackingNo: null,

    showOrderDetail: false,
    orderDetail: {},
    order: {},
  };

  componentDidMount() {
    this.init();
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'paymentOrder/queryList',
      payload: {
        pageNum: 1,
        pageSize: pageSize,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'paymentOrder/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'paymentOrder/queryList',
      payload: {},
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime && fieldsValue.createTime.length) {
        fieldsValue.createOrderTimeStart =
          moment(fieldsValue.createTime[0]).format('YYYY-MM-DD') + 'T00:00:00Z';
        fieldsValue.createOrderTimeEnd =
          moment(fieldsValue.createTime[1]).format('YYYY-MM-DD') + 'T23:59:59Z';
      } else if (!fieldsValue.createTime || !fieldsValue.createTime.length) {
        delete fieldsValue.createOrderTimeStart;
        delete fieldsValue.createOrderTimeEnd;
      }

      delete fieldsValue['createTime'];

      if (fieldsValue.payMethod) {
        fieldsValue.payMethod = parseInt(fieldsValue.payMethod);
      }

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: pageSize,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'paymentOrder/queryList',
        payload: values,
      });
    });
  };

  async handleExport() {
    const { id, status } = this.state;

    const params = {};

    const { form } = this.props;

    form.validateFields(async (err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime && fieldsValue.createTime.length) {
        fieldsValue.createOrderTimeStart =
          moment(fieldsValue.createTime[0]).format('YYYY-MM-DD') + 'T00:00:00Z';
        fieldsValue.createOrderTimeEnd =
          moment(fieldsValue.createTime[1]).format('YYYY-MM-DD') + 'T23:59:59Z';
      } else if (!fieldsValue.createTime || !fieldsValue.createTime.length) {
        delete fieldsValue.createOrderTimeStart;
        delete fieldsValue.createOrderTimeEnd;
      }

      delete fieldsValue['createTime'];

      if (fieldsValue.payMethod) {
        fieldsValue.payMethod = parseInt(fieldsValue.payMethod);
      }

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: pageSize,
      };

      await orderExport(values);
    });
  }

  handleCancel = e => {
    this.setState({
      orderCancel2Show: false,
      orderPaymentShow: false,
      orderSendShow: false,
    });
  };

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('createTime')(
                <RangePicker
                  style={{ width: '100%' }}
                  placeholder={['订单开始时间', '订单结束时间']}
                />
              )}
            </FormItem>
          </Col>

          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('orderNo')(<Input placeholder="订单号 或者 支付号" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('memberName')(<Input placeholder="用户标识" />)}
            </FormItem>
          </Col>

          <Col md={3} sm={24}>
            <FormItem label="">
              {getFieldDecorator('payMethod')(
                <Select style={{ width: '100%' }} placeholder="支付方式">
                  {PAY_TYPE_ARR.map(item => {
                    return (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={3} sm={24} style={{ padding: '0' }}>
            <FormItem label="">
              {getFieldDecorator('status')(
                <Select style={{ width: '100%' }} placeholder="订单状态">
                  {STATUS_ARR.map(item => {
                    return (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <span style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              &nbsp;
              <Button type="primary" onClick={this.handleExport.bind(this)}>
                导出
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleEdit(item) {
    const contentBlock = htmlToDraft(item.content);
    let editorState = null;
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      editorState = EditorState.createWithContent(contentState);
    }

    this.setState({
      id: item.id,
      title: item.title,
      siteNoticeType: item.siteNoticeType,
      modalVisible: true,
      editorState,
    });
  }

  isDatetimeDisabled() {
    if (this.state.siteNoticeType == 'SCHEDULED') {
      return false;
    }

    return true;
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleSelectOnchange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(e) {
    this.setState({
      siteNoticeType: e.target.value,
    });
  }

  onOk() {}

  handlePublish(item) {
    const { dispatch } = this.props;
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  buildBtns(item) {
    const map = {
      0: () => {
        return (
          <span>
            <a href="javascript:;" onClick={this.orderCancel.bind(this, item)}>
              取消
            </a>
          </span>
        );
      },
      1: () => {
        return (
          <span>
            <a href="javascript:;" onClick={this.orderConfirm.bind(this, item)}>
              确认
            </a>&nbsp;
            <a href="javascript:;" onClick={this.orderCancel2Show.bind(this, item)}>
              取消
            </a>
          </span>
        );
      },
      2: () => {
        return (
          <span>
            <a href="javascript:;" onClick={this.orderRequest.bind(this, item)}>
              请款
            </a>
          </span>
        );
      },
      3: () => {
        return (
          <span>
            <a href="javascript:;" onClick={this.requestConfirm.bind(this, item)}>
              请款确认
            </a>
          </span>
        );
      },
      4: () => {
        return (
          <span>
            <a href="javascript:;" onClick={this.orderSendShow.bind(this, item)}>
              寄送
            </a>
          </span>
        );
      },
      5: () => {
        return <span />;
      },
      10: () => {
        return <span />;
      },
      11: () => {
        return (
          <span>
            <a href="javascript:;" onClick={this.orderRefund.bind(this, item)}>
              退款
            </a>
          </span>
        );
      },
      12: () => {
        return <span />;
      },
      31: () => {
        return (
          <span>
            <a href="javascript:;" onClick={this.orderPaymentShow.bind(this, item)}>
              缴费
            </a>
          </span>
        );
      },
    };

    if (map[item.status]) {
      return map[item.status].apply(this);
    }
  }

  async requestConfirm(item) {
    confirm({
      title: '确认信息',
      content: '您是否确定要请款确认？',
      onOk: (async () => {
        let { code, message, data } = await requestConfirm({
          orderNo: item.orderSn,
        });
        if (code === 200) {
          message.success('请款确认成功');
          this.init();
        } else {
          return message.error(message);
        }
      }).bind(this),
      onCancel() {},
    });
  }

  async orderCancel(item) {
    confirm({
      title: '确认信息',
      content: '您是否确定需要取消该笔订单业务？',
      onOk: (async () => {
        let { code, message, data } = await orderCancel({
          orderNo: item.orderSn,
        });
        if (code === 200) {
          message.success('取消成功');
          this.init();
        } else {
          return message.error(message);
        }
      }).bind(this),
      onCancel() {},
    });
  }

  async orderCancel2Show(item) {
    this.setState({
      orderCancel2Show: true,
      activeItem: item,
    });
  }

  async orderCancel2() {
    const { orderCancel2Remark, activeItem } = this.state;
    if (!orderCancel2Remark) {
      return message.error('请备注取消原因');
    }
    let { code, message, data } = await orderCancel({
      orderNo: activeItem.orderSn,
      remark: orderCancel2Remark,
    });
    if (code === 200) {
      message.success('取消成功');
      this.init();
    } else {
      return message.error(message);
    }
  }

  async orderConfirm(item) {
    confirm({
      title: '确认信息',
      content: '请确认承接该笔订单业务.',
      onOk: (async () => {
        let { code, message, data } = await orderConfirm({
          orderNo: item.orderSn,
        });
        if (code === 200) {
          message.success('确认成功');
          this.init();
        } else {
          return message.error(message);
        }
      }).bind(this),
    });
  }

  async orderRequest(item) {
    confirm({
      title: '确认信息',
      content: '请确认请款',
      onOk: (async () => {
        let { code, message, data } = await orderRequest({
          orderNo: item.orderSn,
        });
        if (code === 200) {
          message.success('确认成功');
          this.init();
        } else {
          return message.error(message);
        }
      }).bind(this),
    });
  }

  async orderPaymentShow(item) {
    this.setState({
      orderPaymentShow: true,
      activeItem: item,
    });
  }

  async handleOrderPayment() {
    const { orderPaymentRemark, activeItem, paymentStatus } = this.state;
    if (!orderPaymentRemark) {
      return message.error('请填写备注信息');
    }
    let { code, message, data } = await orderPayment({
      orderNo: activeItem.orderSn,
      paymentStatus,
      remark: orderPaymentRemark,
    });
    if (code === 200) {
      message.success('确认成功');
      this.init();
      this.setState({
        orderPaymentShow: false,
      });
    }
  }

  async orderSendShow(item) {
    this.setState({
      orderSendShow: true,
      activeItem: item,
    });
  }

  async orderSend() {
    const { activeItem, needBilling, invoiceAddress, trackingNo } = this.state;
    if (needBilling === 1) {
      if (!invoiceAddress) {
        return message.error('请填写寄送地址');
      }
      if (!trackingNo) {
        return message.error('请填写快递单号');
      }
    }
    let { code, message, data } = await orderSend({
      orderNo: activeItem.orderSn,
      paymentStatus: needBilling,
      invoiceAddress,
      trackingNo,
    });
    if (code === 200) {
      this.setState({
        orderSendShow: false,
      });
      message.success('保存成功');
      this.init();
    }
  }

  async orderRefund(item) {
    confirm({
      title: '退款确认',
      content: '请对退款订单予以确认，确认后系统将原路退还用户支付金额，还将短信通知用户。',
      onOk: (async () => {
        let { code, message, data } = await orderRefund({
          orderNo: item.orderSn,
        });
        if (code === 200) {
          message.success('确认成功');
          this.init();
        } else {
          return message.error(message);
        }
      }).bind(this),
    });
  }

  async handleShowDetail(item) {
    const { code, message, data } = await orderDetail({
      orderId: item.id,
    });
    if (code === 200) {
      this.setState({
        showOrderDetail: true,
        orderDetail: {
          list: data,
        },
        order: item,
      });
    }
  }

  handleVisible(visible) {
    this.setState({
      [visible]: !this.state[visible],
    });
  }

  render() {
    let { paymentOrder: { data }, loading } = this.props;
    const { selectedRows, modalVisible, orderCancel2Show } = this.state;

    const columns = [
      {
        title: '订单时间',
        dataIndex: 'createTime',
        width: 110,
        render: val => (
          <span>
            {moment(val).format('YYYY-MM-DD')}
            <br />
            {moment(val).format('HH:mm:ss')}
          </span>
        ),
      },
      {
        title: '订单号/支付号',
        dataIndex: 'orderSn',
        width: 240,
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleShowDetail.bind(this, item)}>
              {item.orderSn}
            </a>
            <br />
            {item.payTn || '-'}
          </span>
        ),
      },
      {
        title: '用户标识',
        dataIndex: 'memberName',
      },
      {
        title: '订单金额(元)',
        dataIndex: 'totalAmount',
      },
      {
        title: '代缴费用(元)',
        dataIndex: 'paymentAmount',
      },
      {
        title: '服务费用(元)',
        dataIndex: 'serviceAmount',
      },
      {
        title: '支付方式',
        dataIndex: 'payMethod',
        width: 70,
        render: val => <span>{PAY_TYPE_MAP[val]}</span>,
      },
      {
        title: '支付金额',
        dataIndex: 'actualAmount',
      },
      {
        title: '订单状态',
        dataIndex: 'status',
        width: 70,
        render: val => <span>{STATUS_MAP[val]}</span>,
      },
      {
        title: '操作',
        dataIndex: 'a',
        render: (val, item) => this.buildBtns(item),
      },
    ];

    return (
      <PageHeaderLayout title="缴费订单">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>

            <StandardTable
              size={'small'}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          style={{ width: '800px' }}
          title="确认信息"
          visible={this.state.orderCancel2Show}
          onOk={this.orderCancel2.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" title="您是否确定取消该笔订单业务,请备注取消原因" col="1">
            <TextArea
              style={{ margin: '0 20px', width: 'calc(100% - 40px)' }}
              rows={4}
              value={this.state.orderCancel2Remark}
              onChange={this.handleOnchange.bind(this, 'orderCancel2Remark')}
            />
          </DescriptionList>
        </Modal>

        <Modal
          style={{ width: '800px' }}
          title="确认信息"
          visible={this.state.orderPaymentShow}
          onOk={this.handleOrderPayment.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" col="1">
            <Description term={'缴费状态'}>
              <Select
                value={this.state.paymentStatus}
                onChange={this.handleSelectOnchange.bind(this, 'paymentStatus')}
                placeholder="请选择"
                style={{ width: '100%' }}
              >
                {PAYMENT_STATUS_ARR.map(item => {
                  return (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Description>
            <Description term="备注信息" termStyle={styles.top}>
              <TextArea
                rows={4}
                value={this.state.orderPaymentRemark}
                onChange={this.handleOnchange.bind(this, 'orderPaymentRemark')}
              />
            </Description>
          </DescriptionList>
        </Modal>

        <Modal
          style={{ width: '800px' }}
          title="发票寄送"
          visible={this.state.orderSendShow}
          onOk={this.orderSend.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" col="1">
            <Description term="是否需要发票">
              <Select
                value={this.state.needBilling}
                onChange={this.handleSelectOnchange.bind(this, 'needBilling')}
                placeholder="请选择"
                style={{ width: '100%' }}
              >
                {NEED_BILLING_ARR.map(item => {
                  return (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Description>
            <Description term="寄送地址">
              <Input
                value={this.state.invoiceAddress}
                onChange={this.handleOnchange.bind(this, 'invoiceAddress')}
              />
            </Description>
            <Description term="快递单号">
              <Input
                value={this.state.trackingNo}
                onChange={this.handleOnchange.bind(this, 'trackingNo')}
              />
            </Description>
          </DescriptionList>
        </Modal>

        <Modal
          style={{ width: '80%' }}
          width="80%"
          title="订单详情"
          visible={this.state.showOrderDetail}
          onOk={this.handleVisible.bind(this, 'showOrderDetail')}
          onCancel={this.handleVisible.bind(this, 'showOrderDetail')}
        >
          <DescriptionList size="large" title="" col="1">
            {this.state.order.payMethod === 2 && (
              <Description term="线下支付凭证">
                <img style={{ width: '100px' }} src={this.state.order.paymentVoucher} />
              </Description>
            )}

            <StandardTable
              disableSelect={true}
              selectedRows={selectedRows}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              pagination={false}
              data={this.state.orderDetail}
              columns={[
                {
                  title: '序号',
                  dataIndex: 'id',
                },
                {
                  title: '专利号',
                  dataIndex: 'patentNo',
                },
                {
                  title: '专利名称',
                  dataIndex: 'patentTi',
                },
                {
                  title: '费用类型',
                  dataIndex: 'feeType',
                },
                {
                  title: '应缴费',
                  dataIndex: 'shouldFee',
                },
                {
                  title: '是否缴费',
                  dataIndex: 'feeStatus',
                },
                {
                  title: '缴费截止日',
                  dataIndex: 'feeDate',
                },
              ]}
            />
          </DescriptionList>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
